//从京东联盟后台获取

const log = require('../../util/log')
const config = require('../../util/config')
const chromeMng = require('../chromeMng.20180824')
const {
  Network,
  Page,
  DOM,
  Runtime,
  Emulation
} = chromeMng.client;

async function getJdItems(obj) {
  try {
    obj = obj || {}
    obj.times = (obj.times || 0) + 1
    if (!obj.keyword) {
      return new Promise((resolve, reject) => {
        reject('缺少keyword')
      })
    }
    obj.keyword = obj.keyword.trim()
    log('getting jd items')
    return new Promise((resolve, reject) => {
      chromeMng.loginJd().then(result => {
        step1(obj).then(result => {
          resolve(result)
        }, result => {
          reject(result)
        })
      }, result => {
        reject(result)
      })
    })
  } catch (err) {
    log(err)
  }
}

async function step1(obj) {
  try {
    obj.times++
    if (obj.times >= config.chromeMaxTimes) {
      return new Promise((resolve, reject) => {
        reject('系统错误')
      })
    }
    log('getting jd items step 1')
    Page.navigate({
      url: 'https://media.jd.com/gotoadv/goods?pageSize=50'
    })
    return step1_5(obj)
  } catch (err) {
    log(err)
  }
}

async function step1_5(obj) {
  try {
    obj.times++
    if (obj.times >= config.chromeMaxTimes) {
      return new Promise((resolve, reject) => {
        reject('系统错误')
      })
    }
    log('getting jd items step 1.5')
    var {result} = await Runtime.evaluate({expression: 'location.href'})
    if (result.value == 'https://media.jd.com/gotoadv/goods?pageSize=50') {
      return step2(obj)
    }
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        step1_5(obj).then(result => {
          resolve(result)
        }, result => {
          reject(result)
        })
      }, 1000)
    })
  } catch (err) {
    log(err)
  }
}

async function step2(obj) {
  try {
    obj.times++
    if(obj.times >= config.chromeMaxTimes) {
      return new Promise((resolve, reject) => {
        reject('系统错误')
      })
    }
    log('getting jd items step 2')
    var {result} = await Runtime.evaluate({expression: 'location.href'})
    if (result.value != 'https://media.jd.com/gotoadv/goods?pageSize=50') {
      return step3(obj)
    }
    var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll("#keyword")'})
    var cnt = result.description.substring(9, result.description.length - 1)
    if (cnt == 0) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          step2(obj).then(result => {
            resolve(result)
          }, result => {
            reject(result)
          })
        }, 1000)
      })
    }
    await Runtime.evaluate({expression: 'document.querySelectorAll("#keyword")[0].value="' + obj.keyword + '"'})
    await Runtime.evaluate({expression: 'document.querySelectorAll("#b_search")[0].click()'})
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        step2(obj).then(result => {
          resolve(result)
        }, result => {
          reject(result)
        })
      }, 1000)
    })
  } catch (err) {
    log(err)
  }
}

async function step3(obj) {
  try {
    obj.times++
    if(obj.times >= config.chromeMaxTimes) {
      return new Promise((resolve, reject) => {
        reject('系统错误')
      })
    }
    log('getting jd items step 3')
    var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll(".product-list-b li")'})
    var cnt = result.description.substring(9, result.description.length - 1)
    log(cnt)
    if (cnt == 0) {
      if (Math.random() < 0.1) {
        return new Promise(resolve => {
          resolve([])
        })
      }
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          step3(obj).then(result => {
            resolve(result)
          }, result => {
            reject(result)
          })
        }, 1000)
      })
    }
    var items = []
    for (var i = 0; i < cnt; i++) {
      var item = {}
      var prefix = 'document.querySelectorAll(".product-list-b li")[' + i + '].'
      var {result} = await Runtime.evaluate({expression: prefix + 'querySelectorAll("img")[0].src'})
      if (!result.value) {
        log(i, result)
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            step3(obj).then(result => {
              resolve(result)
            }, result => {
              reject(result)
            })
          }, 1000)
        })
      }
      item.img = result.value
      var {result} = await Runtime.evaluate({expression: prefix + 'querySelectorAll(".tit")[0].innerText'})
      if (!result.value) {
        continue
      }
      item.title = result.value
      var {result} = await Runtime.evaluate({expression: prefix + 'querySelectorAll(".img-wrap>a")[0].href'})
      if (!result.value) {
        log(i, result)
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            step3(obj).then(result => {
              resolve(result)
            }, result => {
              reject(result)
            })
          }, 1000)
        })
      }
      item.link = result.value
      var {result} = await Runtime.evaluate({expression: prefix + 'querySelectorAll(".pri")[0].innerText'})
      if (!result.value) {
        log(i, result)
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            step3(obj).then(result => {
              resolve(result)
            }, result => {
              reject(result)
            })
          }, 1000)
        })
      }
      item.price = parseFloat(result.value.substring(1).replace(/,/i, ''))
      var {result} = await Runtime.evaluate({expression: prefix + 'querySelectorAll(".rate>em")[0].innerText.trim()'})
      if (!result.value) {
        log(i, result)
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            step3(obj).then(result => {
              resolve(result)
            }, result => {
              reject(result)
            })
          }, 1000)
        })
      }
      item.rate = result.value.substring(0, result.value.length - 1)
      var {result} = await Runtime.evaluate({expression: prefix + 'querySelectorAll(".shop")'})
      var _cnt = result.description.substring(9, result.description.length - 1)
      if (_cnt == 1) {
        item.shopName = '京东自营'
      }
      var {result} = await Runtime.evaluate({expression: prefix + 'querySelectorAll(".shop-name")'})
      var _cnt = result.description.substring(9, result.description.length - 1)
      if (_cnt == 1) {
        var {result} = await Runtime.evaluate({expression: prefix + 'querySelectorAll(".shop-name")[0].innerText'})
        item.shopName = result.value
      }
      items.push(item)
    }
    return new Promise(resolve => {
      resolve(items)
    })
  } catch (err) {
    log(err)
  }
}

module.exports = getJdItems
